package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.constant.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/** 登录拦截器负责拦截需要登录的请求
 * date: 2023/9/7 22:22
 * author: MR.孙
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    //因为LoginInterceptor没有被Spring管理，所以不能直接通过依赖注入StringRedisTemplate【使用构造器方式】
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /**
         * 拦截所有请求,主要职责:
         *  获取token，获取不到放行
         *  获取用户信息，获取不到放行 这些都会由登录拦截器判断
         *  保存到ThreadLocal
         *  刷新token有效期
         *  放行
         *
         */

        String token = request.getHeader("authorization");

        if (StrUtil.isBlank(token)) {
            return true;
        }

        String key = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);

        //用户不存在
        if (userMap.isEmpty()) {
            return true;
        }

        //将map转换为bean Map<?, ?> map, T bean, boolean isIgnoreError
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        //用户信息保存到ThreadLocal
        UserHolder.saveUser(userDTO);

        //刷新token有效期
        stringRedisTemplate.expire(key, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //每个请求Tomcat的独立线程，要移除数据 否则会造成内存泄露
        UserHolder.removeUser();
    }
}
